import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:wch/page/home.dart';
import 'package:wch/page/setting.dart';

import '../constant/resource_constant.dart';
import '../utils/toast_utils.dart';
import '../widget/lazy_indexed_stack.dart';

class TabNavigator extends StatefulWidget {
  const TabNavigator({super.key});

  @override
  State<TabNavigator> createState() => _TabNavigatorState();
}

class _TabNavigatorState extends State<TabNavigator> {

  ///用于安卓点2次返回键退出
  DateTime _lastPressedAt = DateTime(2023);

  int curIndex = 0;

  final LazyIndexedStackController stackController = LazyIndexedStackController();

  late List<PageBean> _tabs;
  ///tab 切换产生的事件管理类
  late TabManager tabManager;

  @override
  void initState() {
    super.initState();
    tabManager = TabManager(curIndex);

    _tabs = [
      PageBean(
        '主页',
            (context) => HomePage(),
      ),
      PageBean(
        '设置',
            (context) => SettingPage(id: '',),
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
        value: tabManager,
        child: Consumer<TabManager>(
          builder: (context, entity, child) {
            return Scaffold(
              backgroundColor: Colors.white,
              body: WillPopScope(
                onWillPop: exitApp,
                child: LazyIndexedStack(///延迟加载，当用户未登录时，不会去调用 minePage.dart 的接口
                  controller: stackController,
                  itemSize: _tabs.length,
                  itemBuilder: (context, index) {
                    return _tabs[index].builder.call(context);
                  },
                ),
              ),
              bottomNavigationBar: getBottomItem(entity),
            );
          },
        )
    );
  }

  ///底部 item
  Widget getBottomItem(TabManager entity) {
    List<String> unselectedImages = [
      tabReportUnselect,
      tabMineUnselect,
    ];
    List<String> selectedImages = [
      tabReportSelected,
      tabMineSelected,
    ];
    List<String> texts = ['睡眠报告', '我的'];

    return Container(
      height: 72.h,
      color: const Color(0xFF11191B),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: List.generate(2, (index) {
          return InkWell(
            onTap: () {
              entity.curIndex = index;
              entity.notifyListeners();
              stackController.jumpTo(index);
            },
            child: SizedBox(
              width: ScreenUtil().screenWidth/2,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Padding(padding: EdgeInsets.only(top: 5)),
                  Image.asset(
                    entity.curIndex == index
                        ? selectedImages[index]
                        : unselectedImages[index],
                    width: 24,
                    height: 24,
                    fit: BoxFit.contain,
                  ),
                  Text(
                    texts[index],
                    style: TextStyle(
                        fontSize: fontSizeSmall,
                        color: entity.curIndex == index
                            ? themeColor
                            : const Color(0xFF4E586B)
                    ),
                  ),
                ],
              ),
            ),
          );
        }),
      ),
    );
  }

  Future<bool> exitApp() {
    if (DateTime.now().difference(_lastPressedAt) > const Duration(seconds: 2)) {
      ToastUtils.showToast(
          msg: "再按一次退出应用");
      //两次点击间隔超过2秒则重新计时
      _lastPressedAt = DateTime.now();
      return Future.value(false);
    }
    return Future.value(true);
  }
}

class TabManager extends ChangeNotifier {
  ///当前 tab 下标
  int _curIndex = 0;
  ///传递 int 数据1
  int postInt = 0;
  ///传递 int 数据2
  int post2Int = 0;
  ///传递 int 数据3
  int post3Int = 0;
  ///传递 string 数据
  String postString = '';

  TabManager(this._curIndex);

  set curIndex(int value) {
    _curIndex = value;
    notifyListeners();
  }

  int get curIndex => _curIndex;
}

class PageBean {
  final String name;
  final Widget Function(BuildContext context) builder;
  PageBean(this.name, this.builder);
}
